package com.xhtt.modules.sys.schedule;

import com.alibaba.fastjson.JSON;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.DateUtils;
import com.xhtt.common.utils.MyWebSocket;
import com.xhtt.modules.sys.entity.SysUserPosition;
import com.xhtt.modules.sys.service.SysUserPositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class UserPositionSchedule {
    @Autowired
    private SysUserPositionService sysUserPositionService;
    @Autowired
    private MyWebSocket webSocket;

    @Scheduled(fixedDelay = 10 * 1000)
    public void getUserPosition() {
        try {
            String time = LocalDateTime.now().plusMinutes(-2).format(DateUtils.dtf);//只获取最近2分钟内有刷新的用户
            List<SysUserPosition> list = sysUserPositionService.getUserPosition(time);
            Constant.userPositionList.clear();
            Constant.userPositionList.addAll(list);
        } catch (Exception e) {
            log.error("获取位置信息异常:" + e.getMessage());
        }
        Constant.webSocketSessionQueue.removeIf(session -> session.isActive()==false);
        for(Session session : Constant.webSocketSessionQueue)
        {
            try {
                webSocket.onMessage(session, JSON.toJSONString(Constant.userPositionList));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
